<template>
  <div class="register_panel">
    <InputBox icon="ri-user-line" placeholder="用户名/邮箱/手机号码" v-model:value="username" :on-enter="register"/>
    <InputBox icon="ri-lock-line" placeholder="密码" type="password" v-model:value="password" :on-enter="register"/>
    <InputBox icon="ri-key-fill" placeholder="验证码" v-model:value="captcha" :on-enter="register"
              :button="captchaManager.captcha.countDown || captchaManager.captcha.text" :button-on-click="getCaptcha"/>
    <div class="submit_panel">
      <SubmitButton primary-color="#eac606" @click="register">注册</SubmitButton>
    </div>
  </div>
</template>

<script>
import {reactive, toRefs} from "vue";
import {useRouter} from "vue-router";
import InputBox from "../components/InputBox.vue";
import SubmitButton from "../components/SubmitButton.vue";
import CaptchaManager from "../utils/CaptchaManager.js";
import {apis, tipsPromiseHandler} from "../api";

export default {
  components: {SubmitButton, InputBox},
  setup() {
    const captchaManager = reactive(CaptchaManager.getInstance())
    const router = useRouter()
    const data = reactive({
      username: '',
      password: '',
      captcha: ''
    })

    const register = () => {
      let promise = apis.register(data.username, data.password, data.captcha)
      tipsPromiseHandler(promise, () => router.push('/login'))
    }

    captchaManager.onStart['register'] = ({resolve, reject}) => {
      let promise = apis.getCaptcha(data.username)
      tipsPromiseHandler(promise, resolve, reject)
    }

    const getCaptcha = () => captchaManager.start('register')
    return {...toRefs(data), captchaManager, register, getCaptcha}
  }
}
</script>

<style scoped lang="less">
.register_panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  gap: 20px;

  & .submit_panel {
    margin-top: 10px;
    display: flex;
    gap: 20px;
  }
}
</style>